package com.sptpc.learnspring.service.impl;

import com.sptpc.learnspring.mapper.CategoryMapper;
import com.sptpc.learnspring.model.Category;
import com.sptpc.learnspring.service.ICategoryService;
import com.sptpc.learnspring.vo.CategoryVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
@Slf4j
@CacheConfig(cacheNames = "category")
public class CategoryServiceImpl implements ICategoryService {
    @Autowired
    private CategoryMapper categoryMapper;

    @Override
    @Cacheable
    public List<Category> getAllCategories() {
        List<Category> list = categoryMapper.getAllCategories();
        return list;
    }

    @CacheEvict
    public void reloadCategory() {
        log.info("category缓存已经清理");
    }

    @Override
    public Category addCategory(Category category) {
        categoryMapper.insertSelective(category);
        // 注意下面的调用是无法生效的，
        // 和申明式事务一样，只有方法被外部调用，才能通过AOP增强方法
        // this.reloadCategory();
        return category;
    }

    @Override
    public Category updateCategory(Category category) {
        categoryMapper.updateByPrimaryKey(category);
        return category;
    }

    @Override
    public Category getCategoryById(long id) {
        return categoryMapper.selectByPrimaryKey(id);
    }

    @Override
    public CategoryVO getCategoryWithDrinks(Long id) {
        return categoryMapper.selectByPrimaryKeyWithDrinks(id);
    }
}
